﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using System.Xml;

namespace DE.Sdc.SharePoint.SPContentStructure.Import
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = DeploymentConstants.Namespace)]
    [XmlRoot(Namespace = DeploymentConstants.Namespace, IsNullable = false)]
    public class Fields : IImportDefinition<SPList, SPWeb>
    {
        public Fields()
        {
            Items = new List<Field>();
        }

        [XmlElement("Field")]
        public List<Field> Items { get; set; }

        [XmlIgnore]
        public SPList UpdatedSPObject { get; internal set; }

        /// <summary>
        /// Adds, modifies or deletes fields for a list
        /// </summary>
        /// <param name="list">The parent list where to add, modify or delete the fields</param>
        /// <param name="parentWeb"></param>
        public void ImportDefinition(SPList list, SPWeb parentWeb)
        {
            foreach (Field fieldDefinition in Items)
            {
                SPField field = null;
                try
                {
                    if (!string.IsNullOrEmpty(fieldDefinition.Name))
                        field = list.Fields.GetField(fieldDefinition.Name);
                    else if (fieldDefinition.Id == Guid.Empty)
                        field = list.Fields[fieldDefinition.Id];
                }
                catch (Exception)
                {
                    // Catch if field does not exists
                }

                fieldDefinition.ImportDefinition(field, list);
            }

            UpdatedSPObject = list;
        }
    }
}